package com.ruyuan.user.server.rpc;

import com.ruyuan.common.model.Response;
import com.ruyuan.user.api.UserReadFacade;
import com.ruyuan.user.api.model.enums.UserJobRelationTypeEnum;
import com.ruyuan.user.api.model.response.JobDetailDTO;
import com.ruyuan.user.api.model.response.UserDetailDTO;
import com.ruyuan.user.server.domain.model.Job;
import com.ruyuan.user.server.domain.model.User;
import com.ruyuan.user.server.domain.service.UserDomainService;
import org.apache.commons.collections.MapUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xx
 */
@Service
public class UserReadFacadeImpl implements UserReadFacade {

    @Autowired
    private UserDomainService userDomainService;

    @Override
    public Response<UserDetailDTO> queryUserDetail(Long userId) {
        User user = userDomainService.queryUserById(userId);
        UserDetailDTO userDetailDTO = new UserDetailDTO();
        BeanUtils.copyProperties(user, userDetailDTO);
        Job mainJob = user.getMainJob();
        if (mainJob != null) {
            JobDetailDTO mainJobDTO = new JobDetailDTO();
            BeanUtils.copyProperties(mainJob, mainJobDTO);
            userDetailDTO.setMainJob(mainJobDTO);
        }
        Map<UserJobRelationTypeEnum, List<Job>> otherJobs = user.getOtherJobs();
        if (MapUtils.isNotEmpty(otherJobs)) {
            Map<UserJobRelationTypeEnum, List<JobDetailDTO>> otherJobDTOs = new HashMap<>();
            otherJobs.keySet().forEach(relationType -> {
                List<JobDetailDTO> jobDTOs = otherJobs.get(relationType).stream().map(job -> {
                    JobDetailDTO jobDTO = new JobDetailDTO();
                    BeanUtils.copyProperties(job, jobDTO);
                    return jobDTO;
                }).collect(Collectors.toList());
                otherJobDTOs.put(relationType, jobDTOs);
            });
            userDetailDTO.setOtherJobs(otherJobDTOs);
        }
        return Response.success(userDetailDTO);
    }
}
